#include <QCoreApplication>
#include <QLocalSocket>
#include <QLocalServer>
#include <QApplication>
#include <QTranslator>

#include "window/Window.hpp"

/**
 * 苍眼汉化组
 */
int main(int argc, char* argv[]){
    // 创建程序进程
    QApplication application(argc, argv);

    // 处理命令行参数
    QStringList filepaths;

    if(argc != 1){
        for(int i = 1; i < argc; i++){
            filepaths.push_back(QString::fromLocal8Bit(argv[i]));

        }

    }

    // 程序多开检测
    QString serverName = "goolnn.cangyan";
    QLocalSocket socket;
    socket.connectToServer(serverName);

    if(socket.waitForConnected(500)){
        int count = argc - 1;
        socket.write((char*)&count, 4);

        for(QString filepath: filepaths){
            int size = filepath.toStdString().size() + 1;

            socket.write((char*)&size, 4);
            socket.write(filepath.toStdString().data(), size);

        }

        socket.flush();
        socket.waitForBytesWritten();
        socket.close();
        
        return 0;

    }else{
        QLocalServer server;

        if(server.listen(serverName)){
            if(server.serverError() == QAbstractSocket::AddressInUseError){
                QLocalServer::removeServer(serverName);
                server.listen(serverName);

            }

        }

        // 加载中文翻译
        QTranslator qtTranslator;
        QTranslator qtBaseTranslator;

        if(qtTranslator.load(":/translation/qt_zh_CN.qm")){
            QCoreApplication::installTranslator(&qtTranslator);

        }

        if(qtBaseTranslator.load(":/translation/qtbase_zh_CN.qm")){
            QCoreApplication::installTranslator(&qtBaseTranslator);

        }

        // 显示程序窗口
        Window window(filepaths, &server);
        window.show();

        return application.exec();

    }

}
